package leetCode.thread.leetCode1115;

import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;

/**
 * 基于循环栅栏实现
 */
public class FooBar3 implements FooBar{


    private int n;

    CyclicBarrier cyclicBarrier = new CyclicBarrier(2);
    //用来让foo等待bar的变量
    volatile boolean flag = true;

    @Override
    public void foo(Runnable printFoo) throws InterruptedException {
        for(int i=0;i<n;i++) {
            while (!flag);
            printFoo.run();
            flag = false;
            try{
                cyclicBarrier.await();
            }catch (BrokenBarrierException ignore){

            }
        }
    }

    @Override
    public void bar(Runnable printBar) throws InterruptedException {
        try {
            cyclicBarrier.await();
        }catch (BrokenBarrierException ignore){

        }
        printBar.run();
        flag = true;
    }


}
